import { useEffect, useState, useRef } from 'react';
import { CheckCircle2, XCircle, AlertTriangle, Info } from 'lucide-react';
import './Toast.css';

/**
 * Toast 提示组件
 * @param {string} message - 提示消息
 * @param {string} type - 类型：success, error, warning, info
 * @param {function} onClose - 关闭回调
 * @param {number} duration - 持续时间（毫秒），默认 3000
 */
export const Toast = ({ message, type = 'info', onClose, duration = 3000 }) => {
  const [isExiting, setIsExiting] = useState(false);
  const FADE_OUT_DURATION = 300; // 淡出动画时长（毫秒）
  const closeTimerRef = useRef(null);

  useEffect(() => {
    if (duration > 0) {
      const timer = setTimeout(() => {
        setIsExiting(true);
        // 等待淡出动画完成后再调用 onClose
        closeTimerRef.current = setTimeout(() => {
          onClose?.();
        }, FADE_OUT_DURATION);
      }, duration);
      return () => {
        clearTimeout(timer);
        if (closeTimerRef.current) {
          clearTimeout(closeTimerRef.current);
        }
      };
    }
  }, [duration, onClose]);

  const iconComponents = {
    success: <CheckCircle2 size={24} strokeWidth={2.5} />,
    error: <XCircle size={24} strokeWidth={2.5} />,
    warning: <AlertTriangle size={24} strokeWidth={2.5} />,
    info: <Info size={24} strokeWidth={2.5} />
  };

  return (
    <div className={`toast toast-${type} ${isExiting ? 'toast-exiting' : ''}`}>
      <span className="toast-icon">{iconComponents[type]}</span>
      <span className="toast-message">{message}</span>
    </div>
  );
};

// Toast 容器组件
export const ToastContainer = ({ toasts, removeToast }) => {
  return (
    <div className="toast-container">
      {toasts.map(toast => (
        <Toast
          key={toast.id}
          message={toast.message}
          type={toast.type}
          duration={toast.duration}
          onClose={() => removeToast(toast.id)}
        />
      ))}
    </div>
  );
};

